﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Catalyst.Serialization
{
	public class Serializer
	{
		private static readonly object _lock = new object();

		public static void SerializeContract<T>(string saveFilePath, object obj)
		{
			lock (_lock)
			{
				using (FileStream fs = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
				{
					DataContractSerializer serializer = new DataContractSerializer(typeof(T));
					serializer.WriteObject(fs, obj);
				}
			}
		}

		public static T DeserializeContract<T>(string filePath) where T : class, new()
		{
			using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
			{
				DataContractSerializer serializer = new DataContractSerializer(typeof(T));
				object obj = serializer.ReadObject(fs);
				return (T)obj;
			}
		}

		public static void Serialize(string saveFilePath, object obj)
		{
			lock (_lock)
			{
				using (FileStream fs = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
				{
					BinaryFormatter formatter = new BinaryFormatter();
					formatter.Serialize(fs, obj);
				}
			}
		}

		public static T Deserialize<T>(string filePath) where T : class, new()
		{
			using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
			{
				BinaryFormatter formatter = new BinaryFormatter();
				object obj = formatter.Deserialize(fs);

				return (T)obj;
			}
		}
	}
}
